package zzxkj.blog.service.Impl;
import cn.hutool.core.util.RandomUtil;
import com.github.javafaker.Faker;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import zzxkj.blog.common.lang.Consts;
import zzxkj.blog.imChat.vo.ImMess;
import zzxkj.blog.imChat.vo.ImUser;
import zzxkj.blog.service.ChatService;
import zzxkj.blog.shiro.AccountProfile;
import zzxkj.blog.utils.RedisUtil;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 聊天处理实现类
 * @author zzxkj
 */
@Slf4j
@Service("chatService")
public class ChatServiceImpl implements ChatService {
    public static final String GUEST_INFO_SESSION_KEY = "GUEST_KEY";
    final
    HttpSession httpSession;
    final
    RedisUtil redisUtil;
    final
    Faker faker;
    final
    HttpSession session;

    public ChatServiceImpl(HttpSession httpSession, RedisUtil redisUtil, Faker faker, HttpSession session) {
        this.httpSession = httpSession;
        this.redisUtil = redisUtil;
        this.faker = faker;
        this.session = session;
    }

    @Override
    public ImUser getCurrentUser() {
        ImUser imUser = new ImUser();
        AccountProfile profile = (AccountProfile) SecurityUtils.getSubject().getPrincipal();
        if(profile != null){
            //登录用户
            log.info("登录用户:{}",profile.toString());
            imUser.setId(profile.getId());
            imUser.setAvatar(profile.getAvatar());
            imUser.setUsername(profile.getNickname());
            imUser.setStatus(ImUser.ONLINE_STATUS);
        }else if (session.getAttribute(GUEST_INFO_SESSION_KEY) == null){
            imUser.setAvatar("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2F80%2Fv2-c1748343e68d08167b4c950fb54c4bf6_720w.jpg%3Fsource%3D1940ef5c&refer=http%3A%2F%2Fpic1.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655687562&t=4d26dcc52720aa047937f48b0495013d");
            imUser.setId(RandomUtil.randomLong());
            imUser.setSign("go go go!!!");
            imUser.setUsername("（匿名用户）——" + faker.name().fullName());
            session.setAttribute(GUEST_INFO_SESSION_KEY, imUser);
        }else{
            imUser = (ImUser) session.getAttribute(GUEST_INFO_SESSION_KEY);
            log.info("session guest info:{}", imUser.toString());
        }
        return imUser;
    }

    @Override
    public void setGroupHistoryMsg(ImMess imMess) {
        redisUtil.lSet(Consts.IM_GROUP_HISTROY_MSG_KEY, imMess, 24 * 3600);
    }

    @Override
    public List<Object> getGroupHistoryMsg(int count) {
        long length = redisUtil.lGetListSize(Consts.IM_GROUP_HISTROY_MSG_KEY);
        return redisUtil.lGet(Consts.IM_GROUP_HISTROY_MSG_KEY, length - count < 0 ? 0 : length - count, length);
    }
}
